<template>
  <div class="audio_warp">
    <audio :src="mulitSounrAddress" id="multi-warning-tone"></audio>
    <audio :src="emailSoundAddress" id="email-warning-tone"></audio>
    <audio :src="webchatNewSoundAddress" id="webchat-warning-tone"></audio>
  </div>
</template>
<script type='text/javascript'>
import {deepClone, isHasMenu} from '@/utils/m7Utils.js'
// 判断附件上传到七牛，还是上传到私有云服务器的 判断取本地的东西还是服务器的东西
import {m7UpHosts} from '@/utils/qiniuUtils'
import bus from '@/store/eventBus'
import * as typesGl from '@/store/mutation-types.js'
  import {m7Language} from '@/utils/m7Utils'
import kfNotifyLogo from './../../../assets/img/kf_logo_notify.png'
import {monitorCallConfig, monitorWebchatConfig} from '@/utils/monitor'
import {throttle} from 'lodash'
export default({
  name: 'notify',
  data () {
    return {
      emailSoundAddress: '//fs-im-kefu.7moor.com/emailsound.mp3',
      mulitSounrAddress: '//fs-im-kefu.7moor.com/warning.mp3',
      webchatNewSoundAddress: '/static/audio/im/new.wav',
      monitorData: {
        webChat: {},
        call: {}
      },
      condition: {
        over: '大于',
        less: '小于',
        equal: '等于'
      },
      throttleObj: [{fun: '', val: 'cdr'}, {val: 'business', fun: ''}, {val: 'emailTimeOut', fun: ''}, {val: 'email', fun: ''}, {val: 'customerPlan', fun: ''}, {val: 'quesNotify', fun: ''}, {val: 'saleChance', fun: ''}, {val: 'leakAssignMsg', fun: ''}, {val: 'remoteAssistType', fun: ''}], // 需要节流的模块
      title: '', // 当前页面的title
      titleMessages: '',
      timer: null,
      action: null,
      clearSetIntervalCdr: '',
      clearSetIntervalLeak: '',
      emailTabName: '',
      emailRoute: false, // email 当前模块
      clearSetIntervalWebchat: '',
      clearSetIntervalEmail: '',
      titleText: [] // 闪烁文案
    }
  },
  computed: {
    // 判断是否设置logo
    customLogo () {
      return this.$getCache('customLogo')
    },
    notify () {
      return this.$store.state.notify
    },
    newNotify () {
      console.log(this.notify)
      let notify = this.notify
      let tag = notify.tag
      let temp = {}
      temp.tag = tag
      switch (tag) {
        case 'cdr':
          let NOcallnum = notify.NOcallnum
          // let titleCdr = this.$t('notify.call1') + NOcallnum + this.$t('notify.call2')
          let titleCdr = this.$t('notify.callNotity', {NOcallnum})
          let contentCdr = this.$t('notify.call3')
          temp = {
            tag: tag,
            title: titleCdr,
            content: contentCdr,
            route: '/index/call/cdr_call/' + notify.id + '/cdr?flag=notify'
          }
          break
        case 'webchat':
          let fromSource = this.$t('notify.unKnow')
          let notifyObj = notify.notify
          let routeWebchat = '/index/webchat/webchat_todo/' + notifyObj._id + '/webchat?flag=notify'
          let leaveMsg = notifyObj.leavemsg ? true : false
          notifyObj.Platform = notifyObj.Platform || notifyObj.platform
          if (notifyObj.Platform === 'pc') {
            fromSource = this.$t('notify.platformPc')
          } else if (notifyObj.Platform === 'wap') {
            fromSource = this.$t('notify.platformWap')
          } else if (notifyObj.Platform === 'sdk') {
            fromSource = this.$t('notify.platformSdk')
          } else if (notifyObj.Platform === 'weixin') {
            fromSource = this.$t('notify.platformWeixin')
          } else if (notifyObj.Platform === 'wxmini') {
            fromSource = this.$t('notify.platformWxmini')
          } else if (notifyObj.Platform === 'weibo') {
            fromSource = this.$t('notify.platformWeibo')
          } else if (notifyObj.Platform === 'wxwork') {
            fromSource = this.$t('webchat.enterpriseShot')
          } else if (notifyObj.Platform === 'ocpc') {
            fromSource = this.$t('webchat.baiduBCP')
          } else if (notifyObj.Platform === 'dy') {
            fromSource = this.$t('webchat.TikTok')
          } else if (notifyObj.Platform === 'wxkf') {
            fromSource = this.$t('webchat.platformWXKF')
          }
          let titleWebchat = this.$t('notify.webChatNotity', {fromSource: fromSource, sName: notifyObj.sName})
          let contentWebchat = ''
          if (notifyObj.msgType === 'disConn') {
            contentWebchat = this.$t('notify.webchat10')
          } else if (notifyObj.msgType === 'newConn') {
            contentWebchat = this.$t('notify.webchat11')
          } else if (notifyObj.operation === 'changePeer' || notifyObj.MsgType === 'convertManual') {
            contentWebchat = this.$t('notify.webchat12')
          } else if (notifyObj.operation === 'redirect') {
            contentWebchat = this.$t('notify.webchat19')
          } else if (notifyObj.operation === 'invited') {
            routeWebchat = '/index/webchat/webchat_todo'
            titleWebchat = this.$t('notify.webchat4Notify', {username: notifyObj.username})
            contentWebchat = this.$t('notify.webchat9')
          } else if (notifyObj.operation === 'grab_redirect') {
            routeWebchat = '/index/webchat/webchat_todo'
            titleWebchat = this.$t('notify.webchat4Notify', {username: notifyObj.toUserName})
            contentWebchat = this.$t('notify.webchat7Notity', {toUserName: notifyObj.toUserName, sName: notifyObj.sName})
          } else if (notifyObj.operation === 'autoClose') {
            titleWebchat = this.$t('notify.webchat14')
            contentWebchat = this.$t('notify.webchat6Notity', {sName: notifyObj.sName})
          } else if (notifyObj.content) {
            contentWebchat = notifyObj.content.replace(/<[^>]*>/g, '')
          }
          if (notifyObj.initiating) { // 座席主动接入会话路由跳转
            this.$router.push(routeWebchat)
          }
          temp = {
            tag: tag + '' + Math.random(),
            title: titleWebchat,
            content: contentWebchat,
            route: routeWebchat,
            leaveMsg: leaveMsg,
            realContent: notifyObj.content,
            msgType: notifyObj.msgType || ''
          }
          if (notify.notify) {
            let {sName, sid, toPeer, Platform, otherParams, firstOtherParams} = notify.notify
            temp.otherInfo = {sName, sid, toPeer, Platform, otherParams, firstOtherParams}
            temp._id = notify.notify._id || ''
          }
          break
        case 'business':
          let titleBusiness = this.$t(notify.notify.type === 'configBusiness' ? 'notify.serviceBusiness1' : 'notify.business1')
          let contentBusiness = notify.notify.msg
          // configBusiness为服务工单并向客户推送
          temp = {
            tag: tag,
            title: titleBusiness,
            content: contentBusiness,
            route: notify.notify.type === 'configBusiness' ? '/index/ServiceBusinessList' : '/index/business'
          }
          break
        case 'emailTimeOut':
          let emailTimeOutTitle = this.$t('notify.emailTimeOut')
          let emailTimeOutContent = notify.notify.msg
          temp = {
            tag: tag,
            title: emailTimeOutTitle,
            content: emailTimeOutContent,
            route: '/index/email/',
            query: {active: 'email_todo', emailNumber: notify.notify.id}
          }
          break
        case 'email':
          let titleEmail = ''
          let contentEmail = ''
          let notifyEmail = notify.notify
          if (notifyEmail.subject) {
            titleEmail = this.$t('notify.email1')
            contentEmail = notifyEmail.subject
          }
          if (notifyEmail.emailStatus === 'fail') {
            titleEmail = this.$t('notify.email2')
            contentEmail = this.$t('notify.email3Notity', {to: notifyEmail.to})
          }
          temp = {
            tag: tag,
            title: titleEmail,
            content: contentEmail,
            route: '/index/email/',
            query: {active: 'email_todo', emailNumber: notifyEmail._id}
          }
          break
        case 'customerPlan':
          console.log(notify)
          let notifyCustomerPlan = notify.notify
          let titleCustomerPlan = notifyCustomerPlan.notifyTime
          let contentCustomerPlan = notifyCustomerPlan.status === 'other' ? this.$t('notify.customerContactPlan1') : this.$t('notify.customerContactPlan', notifyCustomerPlan)
          // /index/customer?active=customer_plan&id=8c0a9390-1292-11ea-adf5-ed83e96f430c&selectVal=
          // /index/customer?active=customer_plan&id=${notify.notify._id}
          temp = {
            tag: tag,
            title: titleCustomerPlan,
            content: contentCustomerPlan,
            route: `/index/customer`,
            query: {custName: notifyCustomerPlan.custName, selectVal: notifyCustomerPlan.type === 'executor' ? 'executor' : '', id: notify.notify._id, active: 'customer_plan', type: notifyCustomerPlan.type}
          }
          break
        case 'quesNotify':
          let titleQuesNotify = this.$t('notify.questionnareRemind')
          let contentQuesNotify = this.$t('notify.callbackQuesLate', {time: notify.notify.notifyTime})
          temp = {
            tag: tag,
            title: titleQuesNotify,
            content: contentQuesNotify,
            route: `/index/questionnaire/questionnaire_my/${notify.notify._id}`
          }
          break
        case 'saleChance':
          let notifySaleChance = notify.notify
          let titleSaleChance = this.$t('notify.saleChance')
          let contentSaleChance = notifySaleChance.content
          temp = {
            tag: tag,
            title: titleSaleChance,
            content: contentSaleChance
          }
          break
        case 'leakAssignMsg':
          let notifyleakAssignMsg = notify.notify
          let titleleakAssignMsg = this.$t('notify.leakAssignMsg')
          let contentleakAssignMsg = notifyleakAssignMsg.msg.Data
          temp = {
            tag: tag,
            title: titleleakAssignMsg,
            content: contentleakAssignMsg,
            route: '/index/call/cdr_pending?flag=notify&pending=leakAssignMsg'
          }
          break
        case 'monitor':
          let data = notify.notify || {}
          let content = ''
          let module = data.module === 'call' ? this.$t('public.call') : this.$t('login.onLineServer')
          let title = module + this.$t('monitor.warningTitle')
          if (data.type === 'newMonitor') {
            let name = this.monitorData[data.module][data.name]
            let condition = this.condition[data.condition]
            let threshold = data.threshold
            content = `检测系统当前的${name}${condition}${threshold}，请及时查看。`
          } else {
            let userName = data.userName
            let busyTypeName = data.busyTypeName
            content = this.$t('monitor.warningContent', {userName, busyTypeName})
          }
          temp = {
            tag: tag + Math.random(),
            title: title,
            content: content
          }
          if (isHasMenu('nav_new_monitor', this.$store.state.session.user) && data.type === 'newMonitor') {
            // 登陆新版监控推送
            temp.route = '/index/monitorNew'
          } else if (data.type === 'newMonitor') {
            // 老版监控，新推送不推
            temp = ''
          }
          break
        case 'monitorNew':
          let notifyData = notify.notify || {}
          const notifyContent = `监控提醒: ${notifyData.queueName}${notifyData.codeName}为${notifyData.queueWaitCount}`
          temp = {
            tag: tag + Math.random(),
            title: '通话监控提醒',
            content: notifyContent
          }
          break
        case 'autoqc':
          let titleAutoqcNotify = '您有一个新质检通知需要处理'
          // let contentQuesNotify = this.$t('notify.callbackQuesLate', {time: notify.notify.notifyTime})
          temp = {
            tag: tag,
            title: titleAutoqcNotify
          }
          if (notify.notify.type.indexOf('Call') > -1 && notify.notify.type !== 'newFailedQcCall') {
            if (isHasMenu('nav_call', this.$store.state.session.user)) {
              temp.route = '/index/call/cdr_all/?active=cdr_all&callId=' + notify.notify._id + '&status=autoqc'
            }
          } else if (notify.notify.type.indexOf('Chat') > -1 && notify.notify.type !== 'newFailedQcChat') {
            if (isHasMenu('nav_webchat', this.$store.state.session.user)) {
              temp.route = '/index/webchat/webchat_all/?active=webchat_all&webchatId=' + notify.notify._id + '&status=autoqcWebchat'
            }
          }
          if (notify.notify.type === 'newQcCall' || notify.notify.type === 'recheckCall' || notify.notify.type === 'newFailedQcCall') {
            temp.content = '您有通话记录质检结果，请及时查看'
          } else if (notify.notify.type === 'rejectAppealCall') {
            temp.content = '您有通话质检申诉被驳回，请及时查看'
          } else if (notify.notify.type === 'newQcChat' || notify.notify.type === 'recheckChat' || notify.notify.type === 'newFailedQcChat') {
            temp.content = '您有会话记录质检结果，请及时查看'
          } else if (notify.notify.type === 'rejectAppealChat') {
            temp.content = '您有会话质检申诉被驳回，请及时查看'
          }
          break
        case 'other':
          let titleOther = ''
          let contentOther = ''
          temp = {
            tag: tag,
            title: titleOther,
            content: contentOther
          }
          break
        case 'remoteAssistType':
          let titleremoteAssist = '远程控制提醒'
          let contentremoteAssist = notify.notify.msg
          temp = {
            tag: tag,
            title: titleremoteAssist,
            content: contentremoteAssist
          }
          break
        case 'notice':
          let _tag = tag + Math.random()
          temp = {
            tag: _tag,
            title: this.$t('workbench.noticeNotifyTitle'),
            content: notify.notify.title,
            route: '/index/workbench?' + 'refreshNotice=' + Math.random()
          }
          break
        case 'exportType':
          let route = ''
          let notifyMes = notify.notify
          if (notifyMes.type === 'business') {
            route = '/index/business/exportTask?active=exportTask'
          } else if (notifyMes.type === 'call') {
            route = '/index/call/cdr_all/callExport'
          } else if (notifyMes.type === 'webchat') {
            route = '/index/webchat/webchat_all/export'
          }
          temp = {
            tag: tag + Math.random(),
            title: notifyMes.exportFlag === 'success' ? this.$t('webchat.exportSuccess') : this.$t('webchat.exportError'),
            content: notifyMes.msg,
            route
          }
          break
        case 'callnotice':
          let notiObj = notify.notify
          let callnoticeroute = ''
          temp = {
            tag: tag + Math.random(),
            title: notiObj.title,
            content: notiObj.content,
            callnoticeroute
          }
          break
      }
      return temp
    },
    notifySwitch () {
      return this.$store.state.notify
    }
  },
  watch: {
    notify () {
      console.log(this.newNotify,'this.newNotify')
      if (this.newNotify) {
        let self = this
        let router = this.$route.path
        let tag = this.newNotify.tag
        let spaceTimeCdr, spaceTimeWebchat, spaceTimeEmail
        let notifyConfig = deepClone(this.$store.state.session.user.notifyConfig)
        let sessionUser = deepClone(this.$store.state.session.user)
        // 获取重复通知时间间隔
        if (notifyConfig && notifyConfig.spaceTimeLength) {
          if (notifyConfig.spaceTimeLength.cdr !== '') {
            spaceTimeCdr = Number((Number(notifyConfig.spaceTimeLength.cdr) + Number(notifyConfig.timeLength.cdrTimeLength)) + '000') // 通话
          }
          if (notifyConfig.spaceTimeLength.webchat !== '') {
            spaceTimeWebchat = Number((Number(notifyConfig.spaceTimeLength.webchat) + Number(notifyConfig.timeLength.webchatTimeLength)) + '000') // 在线
          }
          if (notifyConfig.spaceTimeLength.email !== '') {
            spaceTimeEmail = Number((Number(notifyConfig.spaceTimeLength.email) + Number(notifyConfig.timeLength.emailTimeLength)) + '000') // 邮件
          }
        }
        for (let i in this.throttleObj) {
          if (tag === this.throttleObj[i].val) {
            self.throttleObj[i].fun()
            if (sessionUser && sessionUser.notifyStatus) {
              // 当前是来电通知。并且不在来电模块下且时间间隔不为0下执行
              if (sessionUser.notifyStatus.indexOf('cdr') !== -1 && (tag === 'cdr') && spaceTimeCdr && router.indexOf('cdr_call') === -1 && notifyConfig.spaceTimeLength.cdr !== '0') {
                clearInterval(this.clearSetIntervalCdr)
                let cdrTitle = self.$t('notify.callNotifyTitle')
                let route = self.newNotify.route
                this.clearSetIntervalCdr = window.setInterval(function () {
                  self.throttleObj[0].fun(cdrTitle, route)
                }, spaceTimeCdr)
                // 当前是邮件通知。并且不在邮件模块下且时间间隔不为0下执行
              } else if (sessionUser.notifyStatus.indexOf('email') !== -1 && tag === 'email' && spaceTimeEmail && router.indexOf('email') === -1 && notifyConfig.spaceTimeLength.email !== '0') {
                clearInterval(this.clearSetIntervalEmail)
                let emailTitle = self.$t('notify.emailNotifyTitle')
                let route = self.newNotify.route + self.newNotify.query.active + '/' + self.newNotify.query.emailNumber
                this.clearSetIntervalEmail = window.setInterval(function () {
                  self.throttleObj[3].fun(emailTitle, route)
                }, spaceTimeEmail)
              } else if (sessionUser.notifyStatus.indexOf('cdr') !== -1 && tag === 'leakAssignMsg' && spaceTimeCdr && router.indexOf('cdr_call') === -1 && notifyConfig.spaceTimeLength.cdr !== '0') {
                clearInterval(this.clearSetIntervalLeak)
                let leakAssignTitle = self.$t('notify.callNotifyTitle')
                let route = self.newNotify.route
                this.clearSetIntervalLeak = window.setInterval(function () {
                  self.throttleObj[7].fun(leakAssignTitle, route)
                }, spaceTimeCdr)
              }
            }
            return
          }
        }
        if (self.newNotify.tag.indexOf('webchat') > -1 && self.newNotify.content === self.$t('notify.webchat11')) {
          // 记录在线咨询弹窗提醒出现
          let data = {
            type: 'collectNewWebchatNotify',
            _id: self.notify.notify._id,
            sid: self.notify.notify.sid,
            user: self.notify.notify.user
          }
          self.$store.dispatch('collectEventLog', data)
        }
        self.openNotify()
        // 当前是在线通知。并且不在待领取模块下且时间间隔不为0下执行
        if (sessionUser && sessionUser.notifyStatus && sessionUser.notifyStatus.indexOf('webchat') !== -1 && tag.indexOf('webchat') > -1 && spaceTimeWebchat && router.indexOf('webchat_todo') === -1 && notifyConfig.spaceTimeLength.webchat !== '0') {
          // self.openNotify()
          let route = self.newNotify.route
          clearInterval(this.clearSetIntervalWebchat)
          let webchatTitle = self.$t('notify.webchatNotifyTitle')
          this.clearSetIntervalWebchat = window.setInterval(function () {
            self.openNotify(webchatTitle, route)
          }, spaceTimeWebchat)
        }
      }
    },
    m7UpHosts () {
      this.emailSoundAddress = m7UpHosts ? '/static/audio/im/emailsound.mp3' : '//fs-im-kefu.7moor.com/emailsound.mp3'
      this.mulitSounrAddress = m7UpHosts ? '/static/audio/im/warning.mp3' : '//fs-im-kefu.7moor.com/warning.mp3'
    },
    $route (to, from) {
      let routePath = to.path
      // let tag = this.newNotify.tag
      this.title = document.title
      // if (tag) {
      if (routePath.indexOf('webchat_todo') > -1) { // 在线通知在待领取模块下清除定时
        clearInterval(this.clearSetIntervalWebchat)
      } else if (routePath.indexOf('cdr_call') > -1) { // 来电通知在来电模块下清除定时
        clearInterval(this.clearSetIntervalCdr)
        clearInterval(this.clearSetIntervalLeak)
      } else if (routePath.indexOf('email') > -1) { // 邮件通知在待处理模块下清除定时
        if (this.emailTabName === '' || this.emailTabName === 'email_todo') {
          clearInterval(this.clearSetIntervalEmail)
        }
      }
      // }
    },
    emailTabName () { // 邮件通知在待处理模块下清除定时
      if (this.$route.path.indexOf('email') > -1 && this.emailTabName === 'email_todo') {
        clearInterval(this.clearSetIntervalEmail)
      }
    }
  },
  methods: {
    openNotify (repeatContent, repeatRoute) {
      let sessionUser = deepClone(this.$store.state.session.user)
      let notify = this.newNotify
      console.log(notify,'notify')
      if (!notify) {
        return
      }
      let Notification = window.Notification
      let notifyStatus = true
      let self = this
      let date = Date.parse(new Date()) // 当前时间戳
      let durationTime = 10000 // 通知停留时间
      if (sessionUser && sessionUser.notifyStatus) {
        if (sessionUser.notifyStatus.indexOf('cdr') === -1 && (notify.tag === 'cdr' || notify.tag === 'leakAssignMsg')) {
          notifyStatus = false
        } else if (sessionUser.notifyStatus.indexOf('customer') === -1 && (notify.tag === 'customerPlan' || notify.tag === 'saleChance')) {
          notifyStatus = false
        } else if (sessionUser.notifyStatus.indexOf('business') === -1 && notify.tag === 'business') {
          notifyStatus = false
        } else if (sessionUser.notifyStatus.indexOf('webchat') === -1 && notify.tag.indexOf('webchat') > -1) {
          notifyStatus = false
        } else if (sessionUser.notifyStatus.indexOf('email') === -1 && notify.tag === 'email') {
          notifyStatus = false
        } else if (sessionUser.notifyStatus.indexOf('monitor') === -1 && notify.tag.indexOf('monitor') > -1) {
          notifyStatus = false
        }
      }
      // 设置title闪烁 && 通知条展示时长
      if (sessionUser.notifyConfig && notify.tag) {
        if (repeatRoute) { // 重复提醒展示时长设置
          if (repeatRoute.indexOf('call') > -1) {
            durationTime = Number(sessionUser.notifyConfig.timeLength.cdrTimeLength + '000')
          } else if (repeatRoute.indexOf('webchat') > -1) {
            durationTime = Number(sessionUser.notifyConfig.timeLength.webchatTimeLength + '000')
          } else if (repeatRoute.indexOf('email') > -1) {
            durationTime = Number(sessionUser.notifyConfig.timeLength.emailTimeLength + '000')
          }
        } else {
          if (notify.tag === 'cdr' || notify.tag === 'leakAssignMsg') {
            if (sessionUser.notifyConfig.timeLength.cdrTimeLength !== '') {
              durationTime = Number(sessionUser.notifyConfig.timeLength.cdrTimeLength + '000')
            }
            self.titleText.push({label: this.$t('public.call'), value: 'cdr' + date})
          } else if (notify.tag.indexOf('webchat') > -1) {
            if (sessionUser.notifyConfig.timeLength.webchatTimeLength !== '') {
              durationTime = Number(sessionUser.notifyConfig.timeLength.webchatTimeLength + '000')
            }
            self.titleText.push({label: this.$t('monitor.online'), value: 'web' + date})
          } else if (notify.tag === 'email') {
            if (sessionUser.notifyConfig.timeLength.emailTimeLength !== '') {
              durationTime = Number(sessionUser.notifyConfig.timeLength.emailTimeLength + '000')
            }
            self.titleText.push({label: this.$t('public.mail'), value: 'email' + date})
          } else if (notify.tag === 'business') {
            self.titleText.push({label: this.$t('public.business'), value: 'business' + date})
          } else if (notify.tag === 'customerPlan') {
            self.titleText.push({label: this.$t('public.contactPlan'), value: 'customerPlan' + date})
          }
        }
      }
      // oem
      let flag = this.$store.state.oemObj.oemFlag
      let iconPng = m7UpHosts ? kfNotifyLogo : '//fs-im-kefu.7moor.com/kf_logo_notify.png'
      let iconClass = m7UpHosts ? 'private_notify_icon_bg' : 'notify_icon_bg'
      if (flag !== '') {
        iconPng = ''
        iconClass = ''
      }
      let newTitleTextArr = self.titleText.reverse((a, b) => { // 根据时间大的在前，小的在后
        return b.value - a.value
      })
      let titleMsg = uniqeByKeys(newTitleTextArr, ['label'])
      let titleMsgArr = []
      titleMsg.forEach(item => {
        titleMsgArr.push(item.label)
      })
      let notifyContent = notify.content // 通知内容
      let notifyTitle = notify.title // 通知标题
      if (repeatContent && repeatContent !== '') { // 重复提醒
        notifyContent = ''
        notifyTitle = repeatContent
      }
      let iframeInfo = {
        tag: notify.tag,
        title: notifyTitle,
        body: notifyContent
      }
      if (notify.otherInfo) {
        iframeInfo.otherInfo = notify.otherInfo
      }
      if (notify._id) {
        iframeInfo._id = notify._id
      }
      this.checkIsIframe(iframeInfo)
      if (Notification && Notification.permission === 'granted' && notifyStatus) {
        // 浏览器自带消息通知
        if (this.customLogo[0].navigationLogo) {
          iconPng = this.customLogo[0].navigationLogo
        }
        let notification = new Notification(notifyTitle, {
          dir: 'auto',
          lang: '',
          tag: notify.tag, // 部分chrome59受影响
          renotify: true,
          icon: iconPng,
          body: notifyContent,
          requireInteraction: true // 浏览器不自动关闭，取配置的时间，缺省的话，取10s
        })
        notification.onshow = function () {
          if (sessionUser.notifyConfig && sessionUser.notifyConfig.notifyCheckBox) {
            sessionUser.notifyConfig.notifyCheckBox.forEach(item => { // title闪烁权限控制
              if (notify.tag.indexOf(item) > -1 || notify.tag === 'leakAssignMsg') {
                if (titleMsgArr.length > 0 && document.hidden) { // 不在当前窗口下会执行闪烁方法 && 重复提醒窗口不闪烁
                  self.stopTitle('flag')
                  self.titleFlickerFun(self.$t('notify.titleNotifyOne') + titleMsgArr.toString() + self.$t('notify.titleNotifyTwo')) // 调用title闪烁事件
                }
              }
            })
          }
          setTimeout(notification.close.bind(notification), durationTime)
        }
        notification.onclick = function () {
          window.focus()
          self.notifyClickFun(notify, repeatRoute, notification)
        }
        notification.onclose = function () {}
        notification.onerror = function () {}
      } else if (Notification && Notification.permission === 'denied' && notifyStatus) {
        // 自定义浏览器通知
        if (this.eleNotification) {
          this.eleNotification.close()
        }
        if (sessionUser.notifyConfig && sessionUser.notifyConfig.notifyCheckBox) {
          sessionUser.notifyConfig.notifyCheckBox.forEach(item => { // title闪烁权限控制
            if (notify.tag.indexOf(item) > -1 || notify.tag === 'leakAssignMsg') {
              if (titleMsgArr.length > 0 && document.hidden) { // 不在当前窗口下会执行闪烁方法
                self.stopTitle('flag')
                self.titleFlickerFun(self.$t('notify.titleNotifyOne') + titleMsgArr.toString() + self.$t('notify.titleNotifyTwo')) // 调用title闪烁事件
              }
            }
          })
        }
        const h = this.$createElement
        if (this.customLogo[0].navigationLogo) {
          let navigationLogo = this.customLogo[0].navigationLogo
          this.eleNotification = this.$notify({
            title: notifyTitle,
            dangerouslyUseHTMLString: true,
            message: `<i class="customer_icon" style="background: url(${navigationLogo}) no-repeat 50% 50%; background-size: 100%;"></i><div class="notify_ellipsis" style="width: 17em;">${notifyContent}</div>`,
            customClass: 'custom-notification',
            onClick: function () {
              self.notifyClickFun(notify, repeatRoute)
            },
            duration: durationTime
          })
        } else {
          this.eleNotification = this.$notify({
            title: notifyTitle,
            message: h('div', {style: 'width: 17em;', class: 'notify_ellipsis'}, notifyContent),
            iconClass: iconClass,
            onClick: function () {
              self.notifyClickFun(notify, repeatRoute)
            },
            customClass: 'custom-notification',
            duration: durationTime
          })
        }
      }
      let music
      if (notify.tag === 'email') {
        music = document.getElementById('email-warning-tone')
      } else if (notify.msgType === 'newMsg' && notify.realContent === m7Language('notify.webchat11')) {
        music = document.getElementById('webchat-warning-tone')
      } else {
        music = document.getElementById('multi-warning-tone')
      }
      let isOn = true
      if (window.sessionStorage.getItem('loginData')) {
        let loginForm = JSON.parse(window.sessionStorage.getItem('loginData'))
        if (window.localStorage.getItem(loginForm.loginName)) {
          isOn = JSON.parse(window.localStorage.getItem(loginForm.loginName)).isOn
        }
      }
      if (music && isOn) { // 是否播放音乐     
        let soundFlag = true
        if (notify.tag.indexOf('webchat') > -1 && this.$store.state.session.user && this.$store.state.session.user.notifySound) {
          let notifySound = this.$store.state.session.user.notifySound
          let notifyData = this.notify.notify
          if ((!notifySound.length) || (notifyData.msgType === 'newMsg' && notifyData.contentType && notifySound.indexOf('newMsg') < 0) || (notifyData.msgType === 'newMsg' && !notifyData.contentType && notifySound.indexOf('newSession') < 0) || (notifyData.msgType === 'newConn' && notifySound.indexOf('newConn') < 0) || (notifyData.msgType === 'disConn' && notifySound.indexOf('disConn') < 0)) {
            soundFlag = false
          }
        }
        if ((notify.tag.indexOf('monitor') > -1 || notify.tag === 'email' || notify.tag.indexOf('webchat') > -1) && soundFlag) {
          music.muted = false
          music.volume = 1
          // music.currentTime = 0
          console.log(music)
          let playPromise = music.play()
          if (playPromise !== undefined) { // 异常捕获
            playPromise.then(_ => {
            }).catch(error => {
              console.log(error)
              music.load()
            })
          }
        }
      }
    },
    checkIsIframe(obj) {
      if (window.self !== window.top) {
        window.parent.postMessage(obj, '*');
      }
    },
    notifyClickFun (notify, repeatRoute, notification) {
      let self = this
      let closeClick = document.querySelectorAll('.el-dialog__headerbtn')
      closeClick = Array.prototype.slice.call(closeClick) // 转换为数组
      if (closeClick.length) {
        closeClick.forEach((item) => {
          if (item) {
            item.click()
          }
        })
      }
      this.handleWinFocus() // 清除title 闪烁
      if (repeatRoute) {
        this.$router.push({path: repeatRoute})
        if (repeatRoute.indexOf('cdr_pending') > -1) { // 分配未接来电
          clearInterval(this.clearSetIntervalLeak)
        }
        if (repeatRoute.indexOf('email') > -1) {
          clearInterval(this.clearSetIntervalEmail)
          bus.$emit('emailJumpRoute')  // 邮件跳转路由监听
        }
      } else {
        if (notify.route) {
          if (notify.tag === 'emailTimeOut') {
          // self.$router.push({path: notify.route, query: notify.query, status: 'timeOut'})
            this.$router.push({path: '/index/email/', query: {active: 'email_all', emailNumber: notify.query.emailNumber, status: 'timeOut'}})
            bus.$emit('emailJumpRoute')  // 邮件跳转路由监听
          } else if (notify.tag === 'email') {
            self.$router.push({path: notify.route, query: notify.query})
            clearInterval(this.clearSetIntervalEmail)
            bus.$emit('emailJumpRoute')  // 邮件跳转路由监听
          } else if (notify.tag === 'customerPlan') {
            // 联系计划跳转
            let _query = {
              active: notify.query.active,
              id: notify.query.id,
              selectVal: notify.query.selectVal
            }
            let _obj1 = {
              module: 'customer',
              random: Math.random()
            }
            self.$router.push({path: notify.route, query: _query})
            this.$store.commit(typesGl.NOTICECUSTOMER, _obj1)
            // self.$store.commit('customer/REFRESH_LEFT', Math.random())
            // this.$store.commit('customer/REFRESH_CUST_RIGHT', Math.random())
          } else if (notify.tag.indexOf('webchat') > -1) {
            let isLeaveMsg = notify.leaveMsg
            self.$router.push({path: notify.route, query: {isLeaveMsg: isLeaveMsg}})
            bus.$emit('webchatJumpRoute', notify)
          } else {
            self.$router.push({path: notify.route})
            if (notify.tag === 'leakAssignMsg') { // 分配未接来电清除重复提醒
              clearInterval(this.clearSetIntervalLeak)
            }
          }
        }
      }
      if (notification) {
        notification.close()
      } else {
        self.eleNotification.close()
      }
    },
    initMonitorData () {
      this.$store.dispatch('getProvinceCodes').then((res) => {
        let data = res.data || []
        data = data.map((item) => {
          return {label: item.n, value: 'area_' + item._id}
        })
        // monitorCallConfig.area = data
        let _monitorCallConfig = monitorCallConfig()
        _monitorCallConfig.area = data
        function generate (data) {
          let out = {}
          for (let i in data) {
            let item = data[i]
            if ((typeof data[i]) === 'object') {
              item.forEach((item) => {
                out[item.value] = item.label
              })
            }
          }
          return out
        }
        this.$set(this.monitorData, 'call', generate(_monitorCallConfig))
        this.$set(this.monitorData, 'webChat', generate(monitorWebchatConfig()))
      })
    },
    titleFlickerFun (msg) { // 标题闪烁事件
      if (!this.action) {
        try {
          const element = document.getElementsByTagName('title')[0]
          element.innerHTML = '\u200E'
          this.action = function (title) {
            element.innerHTML = title
          }
        } catch (e) {
          this.action = function (title) {
            document.title = title
          }
        }
      }
      let newTitle = msg + '-{' + this.title + '}'
      this.titleMessages = [newTitle]
      let sTitle = '\u200E'
      this.titleMessages.push(sTitle)
      let self = this
      this.timer = setInterval(function () {
        self.toggleTitle()
      }, 1000)
    },
    toggleTitle () { // 切换title
      this.action(this.titleMessages[this.index = this.index === 0 ? 1 : 0])
    },
    stopTitle (flag) {  // 停止title闪烁
      if (this.timer) {
        clearInterval(this.timer)
        if (!flag) {
          //        this.action(this.title)
          document.title = this.title
        }
        this.timer = null
        this.titleMessages = ''
      }
    },
    handleWinFocus () { // 窗口聚焦事件
      this.stopTitle()
      if (this.$route.path.indexOf('email') > -1) { // 当时邮件模块清除定时
        clearInterval(this.clearSetIntervalEmail)
      } else if (this.$route.path.indexOf('webchat_todo') > -1) { // 当时在线模块清除定时
        clearInterval(this.clearSetIntervalWebchat)
      } else if (this.$route.path.indexOf('cdr_call') > -1) { // 当时来电模块清除定时
        clearInterval(this.clearSetIntervalCdr)
        clearInterval(this.clearSetIntervalLeak)
      }
      this.titleText = []
    },
    handleWinBlur () {
      this.titleText = []
    }
  },
  beforeMount () {
    if (window.Notification) {
      window.Notification.requestPermission()
    }
    this.initMonitorData()
    let self = this
    for (var i in this.throttleObj) {
      this.throttleObj[i].fun = throttle(function (titleContent, route) {
        self.openNotify(titleContent, route)
      }, 500, { 'trailing': false })
    }
    bus.$on('emailClickTabFun', (tabName) => { // 监听邮件tab点击事件
      this.emailTabName = tabName
    })
    window.addEventListener('focus', this.handleWinFocus) // 监听窗口聚焦
    window.addEventListener('blur', this.handleWinBlur) // 监听窗口聚焦
  },
  beforeDestroy () {
    window.removeEventListener('focus', this.handleWinFocus) // 销毁窗口聚焦
    window.removeEventListener('blur', this.handleWinBlur) // 销毁窗口聚焦
    bus.$off('emailClickTabFun')
  }
})
// 将对象元素转换成字符串以作比较
function objkey (obj, keys) {
  let n = keys.length
  let key = []
  while (n--) {
    key.push(obj[keys[n]])
  }
  return key.join('|')
}
// 去重操作
function uniqeByKeys (array, keys) {
  var arr = []
  var hash = {}
  for (var i = 0, j = array.length; i < j; i++) {
    var k = objkey(array[i], keys)
    if (!(k in hash)) {
      hash[k] = true
      arr.push(array[i])
    }
  }
  return arr
}
</script>
<style lang="stylus">
  .custom-notification {
    bottom: 16px !important;
    top: inherit !important;
    z-index: 99999999999 !important;
  }

  .custom-notification .el-notification__closeBtn {
    right: 7px;
    top: 10px;
  }

  .custom-notification .el-notification__title {
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    box-orient: vertical;
    word-break: break-all;
  }
</style>
<style lang="stylus" scoped>
  .audio_warp
    display none
</style>
